package com.csu.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csu.mall.common.dto.AttrTo;
import com.csu.mall.common.utils.PageUtils;
import com.csu.mall.common.utils.Query;
import com.csu.mall.product.Global;
import com.csu.mall.product.dao.*;
import com.csu.mall.product.entity.*;
import com.csu.mall.product.service.AttrService;
import com.csu.mall.product.service.CategoryService;
import com.csu.mall.product.vo.AttrResVo;
import com.csu.mall.product.vo.AttrVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Resource
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Resource
    private AttrGroupDao attrGroupDao;

    @Resource
    private CategoryDao categoryDao;

    @Resource
    private ProductAttrValueDao attrValueDao;

    @Resource
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.eq("attr_id", key).or().like("attr_name", key);
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Long catelogId, Map<String, Object> params, int attrType) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_type", attrType);
        String key = (String) params.get("key");
        if(catelogId != null && catelogId > 0){
            wrapper.eq("catelog_id", catelogId);
        }
        if(!StringUtils.isEmpty(key)){
            wrapper.and(item->{
               item.like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> attrEntities = page.getRecords();
        List<AttrResVo> attrResVoList = attrEntities.stream().map(attrEntity -> {
            AttrResVo attrResVo = new AttrResVo();
            BeanUtils.copyProperties(attrEntity, attrResVo);
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            if(relationEntity != null){
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if(attrGroupEntity != null){
                    attrResVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            CategoryEntity category = categoryDao.selectById(attrEntity.getCatelogId());
            attrResVo.setCatelogName(category.getName());
            return attrResVo;
        }).collect(Collectors.toList());
        pageUtils.setList(attrResVoList);
        return pageUtils;
    }

    @Override
    @Transactional
    public void saveAttr(AttrVo attrVo) {
        AttrEntity attr = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attr);
        this.save(attr);
        // 基本属性才有属性所属的属性分组
        if(attrVo.getAttrType() == Global.AttrType.BASE_ATTR.getCode()){
            //为属性分配了属性分组，才插入数据到 属性-属性分组 表 中
            if(attrVo.getAttrGroupId() != null && attrVo.getAttrGroupId() > 0){
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
                attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
                attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());
                attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
            }
        }

    }

    @Override
    public AttrResVo getAttrResVo(Long attrId) {
        //1.查询属性所属分组
        AttrEntity attrEntity = this.getById(attrId);
        AttrResVo attrResVo = new AttrResVo();
        BeanUtils.copyProperties(attrEntity, attrResVo);
        AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
        if(relationEntity != null){
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
            if(attrGroupEntity != null){
                attrResVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
        }
        //2.查询属性所属分类的层级路径
        Long[] catelogPath = categoryService.getCatelogPath(attrEntity.getCatelogId());
        attrResVo.setCatelogPath(catelogPath);
        return attrResVo;
    }

    @Override
    public void updateAttr(AttrVo attr) {
        //1.更新属性所属分类
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);
        //2.更新属性所属分组
        //2.1先查【属性-属性分组关系表】中是否有记录，没有则做新增，有则做更新
        int total = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        relationEntity.setAttrId(attr.getAttrId());
        relationEntity.setAttrGroupId(attr.getAttrGroupId());
        if(total > 0){
            attrAttrgroupRelationDao.update(relationEntity, new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
        }else {
            attrAttrgroupRelationDao.insert(relationEntity);
        }
    }

    @Transactional
    @Override
    public void updateSpuAttrValueEntity(Long spuId, List<ProductAttrValueEntity> attrValueEntities) {
        //修改 spu 规格参数
        // 1.删除 spuId下对应 的规格参数
        attrValueDao.deleteBySpuId(spuId);

        // 2.新增前端传过来的规格参数
        List<ProductAttrValueEntity> attrValueEntityList = attrValueEntities.stream().map(item->{
            ProductAttrValueEntity attrValueEntity = new ProductAttrValueEntity();
            BeanUtils.copyProperties(item, attrValueEntity);
            attrValueEntity.setSpuId(spuId);
            return attrValueEntity;
        }).collect(Collectors.toList());
        attrValueDao.batchInsert(attrValueEntityList);
    }

    @Override
    public AttrTo getAttrResTo(Long attrId) {
        AttrResVo attrResVo = this.getAttrResVo(attrId);
        AttrTo attrTo = new AttrTo();
        BeanUtils.copyProperties(attrResVo, attrTo);
        return attrTo;
    }

}